﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Smarly.Web.Controllers;
using Smarly.Web.Controllers.Base;

namespace Smarly.Web.ModelBinder
{
	public class SmarlyModelBinder : DefaultModelBinder
	{
		protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
		                                           PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
		{
			var controller = controllerContext.Controller as BaseController;
			if (controller == null)
				return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);

			object propertyValue = null;
			try
			{
				propertyValue = base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
			}
			catch (HttpRequestValidationException)
			{
				var provider = bindingContext.ValueProvider as ValueProviderCollection;
				if (provider != null)
				{
					ValueProviderResult val = provider.GetValue(bindingContext.ModelName, true);
					propertyValue = controllerContext.HttpContext.Server.HtmlEncode(val.AttemptedValue);
				}
				else
				{
					controller.ModelState.AddModelError(propertyDescriptor.Name, "Html тэги запрещенны");
				}
			}

			return propertyValue;
		}
	}
}